<html>
  <head>
    <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>scrollIntoView 实现页面锚点 - Rubin&#39;s Blog</title>
<meta name="description" content="温故而知新" />
<link rel="shortcut icon" href="https://jrb1995.gitee.io/favicon.ico?v=1588066216187">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.10.0/katex.min.css">
<link href="https://cdn.jsdelivr.net/npm/remixicon@1.3.1/fonts/remixicon.css" rel="stylesheet">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Droid+Serif:400,700">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">

<link rel="stylesheet" href="https://jrb1995.gitee.io/styles/main.css">
<link rel="alternate" type="application/atom+xml" title="scrollIntoView 实现页面锚点 - Rubin&#39;s Blog - Atom Feed" href="https://jrb1995.gitee.io/atom.xml">



  </head>
  <body>
    <div id="app" class="main px-4 flex flex-col lg:flex-row">
      <div id="sidebar" class="sidebar-wrapper lg:static lg:w-1/4">
  <div class="lg:sticky top-0">
    <div class="sidebar-content">
      <div class="flex lg:block p-4 lg:px-0 items-center fixed lg:static lg:block top-0 right-0 left-0 bg-white z-50">
        <i class="remixicon-menu-2-line lg:mt-4 text-2xl cursor-pointer animated fadeIn" onclick="openMenu()"></i>
        <a href="https://jrb1995.gitee.io">
          <img class="animated fadeInLeft avatar rounded-lg mx-4 lg:mt-32 lg:mx-0 mt-0 lg:w-24 lg:h-24 w-12 w-12" src="https://jrb1995.gitee.io/images/avatar.png?v=1588066216187" alt="">
        </a>
        <h1 class="animated fadeInLeft lg:text-4xl font-extrabold lg:mt-8 mt-0 text-xl" style="animation-delay: 0.2s">Rubin&#39;s Blog</h1>
      </div>
      
        <div class="animated fadeInLeft" style="animation-delay: 0.4s">
          <p class="my-4 text-gray-600 font-light hidden lg:block">
            文章目录
          </p>
          <div class="toc-container hidden lg:block">
            <ul class="markdownIt-TOC">
<li>
<ul>
<li><a href="#%E5%89%8D%E8%A8%80">前言</a></li>
<li><a href="#%E8%A7%A3%E5%86%B3%E9%97%AE%E9%A2%98">解决问题</a></li>
<li><a href="#%E5%85%B6%E4%BB%96%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF">其他使用场景</a></li>
<li><a href="#%E7%BB%93%E8%AF%AD">结语</a></li>
</ul>
</li>
</ul>

          </div>
        </div>
      
    </div>
  </div>
</div>

<div class="menu-container">
  <i class="remixicon-arrow-left-line text-2xl cursor-pointer animated fadeIn close-menu-btn" onclick="closeMenu()"></i>
  <div>
    
      
        <a href="/" class="menu" style="animation-delay: 0s">
          首页
        </a>
      
    
      
        <a href="/archives" class="menu" style="animation-delay: 0.2s">
          归档
        </a>
      
    
      
        <a href="/tags" class="menu" style="animation-delay: 0.4s">
          标签
        </a>
      
    
      
        <a href="/post/about" class="menu" style="animation-delay: 0.6000000000000001s">
          关于
        </a>
      
    
  </div>
  <div class="site-footer">
    <div class="py-4 text-gray-700">Powered by <a href="https://github.com/getgridea/gridea" target="_blank">Gridea</a></div>
    <a class="rss" href="https://jrb1995.gitee.io/atom.xml" target="_blank">RSS</a>
  </div>
</div>
<div class="mask" onclick="closeMenu()">
</div>
      <div class="content-wrapper py-32 lg:p-8 lg:w-3/4 post-detail animated fadeIn">
        <h1 class="text-3xl font-bold lg:mt-16">scrollIntoView 实现页面锚点</h1>
        <div class="text-sm text-gray-700 lg:my-8">
          2020-01-30 / 3 min read
        </div>
        
        <div class="post-content yue">
          <p>锚点即指 html 中的链接，在页面中适当的添加锚点可以大大提高阅读或查找效率</p>
<!-- more -->
<h2 id="前言">前言</h2>
<p>锚点是网站中常用的功能。前端简单实现锚点的方法，使用 a 标签把 href 属性写成要跳转到的元素 id，比如以下代码：</p>
<pre><code class="language-html">&lt;a href=&quot;#anchor&quot;&gt;&lt;/a&gt;

&lt;div id=&quot;anchor&quot;&gt;&lt;/div&gt;
</code></pre>
<p>点击 a 标签页面就会跳转到指定 id 元素的位置。并改变链接地址比如：<code>http://www.xxxx.com#anchor</code>。</p>
<p>虽然不会有什么问题，直接跳转过去立马完成产品的需求，但是当网页中存在多个锚点时，就会出现点击浏览器后退按钮并不会返回之前浏览的网页，而是返回上一个带有锚点的链接。</p>
<blockquote>
<p>举个例子，当前网站链接是 <code>http://www.xxxx.com#anchor2</code>， 当用户想返回之前的页面，点击后退按钮后，链接变成了 <code>http://www.xxxx.com#anchor1</code>。但还是在同一个页面中，会使用户感到迷惑，降低用户体验。</p>
</blockquote>
<h2 id="解决问题">解决问题</h2>
<p><code>scrollIntoView()</code> 方法让当前的元素滚动到浏览器窗口的可视区域内，详见 <a href="https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView">MDN</a> 对此方法介绍。</p>
<p>简单代码实现：</p>
<pre><code class="language-html">&lt;!-- HTML --&gt;
&lt;div onclick='getAnchor('anchor_1')'&gt;定位到锚点一&lt;/div&gt;
&lt;div onclick='getAnchor('anchor_2')'&gt;定位到锚点二&lt;/div&gt;

&lt;div id='anchor_1'&gt;锚点位置一&lt;/div&gt;
&lt;div id='anchor_2'&gt;锚点位置二&lt;/div&gt;
</code></pre>
<pre><code class="language-js">&lt;!-- JS --&gt;
function getAnchor (id) {
    // 跳转到锚点
    document.getElementById(id).scrollIntoView()
}
</code></pre>
<p>如果需要让页面平滑滚动到指定位置，则需要增加参数 <code>behavior</code> 设置其值为 <code>smooth</code></p>
<pre><code class="language-js">document.documentElement.scrollIntoView({
    behavior: &quot;smooth&quot;,
    block: &quot;start&quot;,
    inline: &quot;nearest&quot;
});
</code></pre>
<h2 id="其他使用场景">其他使用场景</h2>
<p><strong>回到顶部</strong> 也是网页中常用功能。</p>
<p>简单代码实现  <code>document.querySelector('html').scrollIntoView()</code></p>
<h2 id="结语">结语</h2>
<p>本文只是简单介绍了使用方法，想要详细了解的话，可以参考张鑫旭的这篇文章：<a target="_blank" href="https://www.zhangxinxu.com/wordpress/2018/10/scroll-behavior-scrollintoview-%E5%B9%B3%E6%BB%91%E6%BB%9A%E5%8A%A8/">CSS scroll-behavior 和 JS scrollIntoView 让页面滚动平滑</a></p>

        </div>

        
          <a class="animated fadeInUp p-2 items-center text-sm text-gray-700 border hover:bg-gray-300 leading-none rounded-full flex lg:inline-flex m-4 " href="https://jrb1995.gitee.io/tag/pGvoCX5tk/">
            <span class="flex-auto">js</span>
          </a>
        


        <div class="flex justify-between py-8">
          
            <div class="prev-post">
              <a href="https://jrb1995.gitee.io/post/git-commit-message-gui-fan-hua-shi-jian/">
                <h3 class="post-title">
                  <i class="remixicon-arrow-left-line"></i>
                  Git Commit Message 规范化实践
                </h3>
              </a>
            </div>
          

          
            <div class="next-post">
              <a href="https://jrb1995.gitee.io/post/mac-xia-nvm-de-an-zhuang-he-shi-yong/">
                <h3 class="post-title">
                  Mac 下 nvm 的安装和使用
                  <i class="remixicon-arrow-right-line"></i>
                </h3>
              </a>
            </div>
          
        </div>

        
          
            <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
<script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

<div id="gitalk-container"></div>

<script>

  var gitalk = new Gitalk({
    clientID: '58415ac62e821b4b6bbd',
    clientSecret: '69a93aa48149a7a74c6517efbbb32c57bc07799f',
    repo: 'jrb1995.github.io',
    owner: 'jrb1995',
    admin: ['jrb1995'],
    id: (location.pathname).substring(0, 49),      // Ensure uniqueness and length less than 50
    distractionFreeMode: false  // Facebook-like distraction free mode
  })

  gitalk.render('gitalk-container')

</script>

          

          
        

      </div>
    </div>

    <script src="https://jrb1995.gitee.io/media/prism.js"></script>  
<script>

Prism.highlightAll()

let mainNavLinks = document.querySelectorAll(".markdownIt-TOC a");

// This should probably be throttled.
// Especially because it triggers during smooth scrolling.
// https://lodash.com/docs/4.17.10#throttle
// You could do like...
// window.addEventListener("scroll", () => {
//    _.throttle(doThatStuff, 100);
// });
// Only not doing it here to keep this Pen dependency-free.

window.addEventListener("scroll", event => {
  let fromTop = window.scrollY;

  mainNavLinks.forEach((link, index) => {
    let section = document.getElementById(decodeURI(link.hash).substring(1));
    let nextSection = null
    if (mainNavLinks[index + 1]) {
      nextSection = document.getElementById(decodeURI(mainNavLinks[index + 1].hash).substring(1));
    }
    if (section.offsetTop <= fromTop) {
      if (nextSection) {
        if (nextSection.offsetTop > fromTop) {
          link.classList.add("current");
        } else {
          link.classList.remove("current");    
        }
      } else {
        link.classList.add("current");
      }
    } else {
      link.classList.remove("current");
    }
  });
});


document.addEventListener("DOMContentLoaded", function() {
  var lazyImages = [].slice.call(document.querySelectorAll(".post-feature-image.lazy"));

  if ("IntersectionObserver" in window) {
    let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting) {
          let lazyImage = entry.target
          lazyImage.style.backgroundImage = `url(${lazyImage.dataset.bg})`
          lazyImage.classList.remove("lazy")
          lazyImageObserver.unobserve(lazyImage)
        }
      });
    });

    lazyImages.forEach(function(lazyImage) {
      lazyImageObserver.observe(lazyImage)
    })
  } else {
    // Possibly fall back to a more compatible method here
  }
});

const menuContainer = document.querySelector('.menu-container')
const menus = document.querySelectorAll('.menu-container .menu')
const mask = document.querySelector('.mask')
const contentWrapper = document.querySelector('.content-wrapper')
const latestArticle = document.querySelector('.latest-article')
const readMore = document.querySelector('.read-more')
const indexPage = document.querySelector('.index-page')

const isHome = location.pathname === '/'
if (latestArticle) {
  latestArticle.style.display = isHome ? 'block' : 'none'
  readMore.style.display = isHome ? 'block' : 'none'
  indexPage.style.display = isHome ? 'none' : 'block'
}

const openMenu = () => {
  menuContainer.classList.add('open')
  menus.forEach(menu => {
    menu.classList.add('animated', 'fadeInLeft')
  })
  mask.classList.add('open')
  contentWrapper.classList.add('is-second')
}

const closeMenu = () => {
  menuContainer.classList.remove('open')
  menus.forEach(menu => {
    menu.classList.remove('animated', 'fadeInLeft')
  })
  mask.classList.remove('open')
  contentWrapper.classList.remove('is-second')
}
</script>
  
  </body>
</html>
